package dq.study.datasource;

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author dongqun
 * @version 1.0
 * @description 类的功能描述
 * @date 2019/9/23 10:45
 */
public class MyDataSource {
    private static MyDataSource instance;
    private static volatile List<Connection> pool = new LinkedList<Connection>();

    private MyDataSource(){}

    public static MyDataSource getDataSource(){
        if (instance==null){
            synchronized (MyDataSource.class){
                if (instance==null){
                    instance = new MyDataSource();
                }
            }
        }
        return instance;
    }

    static {
        try {
            for (int i = 0; i< 10; i++){
                DriverManager.registerDriver(new SQLServerDriver());
                Connection conn = DriverManager.getConnection("jdbc:sqlserver://192.168.163.167:1433;DatabaseName=apss","sa","Apses2018");
                pool.add(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public synchronized Connection getConnection() throws SQLException {
        if (pool.size()==0){
            try {
                for (int i = 0; i< 5; i++){
                    DriverManager.registerDriver(new SQLServerDriver());
                    Connection conn = DriverManager.getConnection("jdbc:sqlserver://192.168.163.167:1433;DatabaseName=apss","sa","Apses2018");
                    pool.add(conn);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        final Connection conn = pool.remove(0);
        Connection proxy = (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces(), (proxy1, method, args) -> {
            if ("close".equals(method.getName())){
                returnConnection(conn);
                return null;
            }else {
                return method.invoke(conn,args);
            }
        });
        System.out.println("拿出一个连接，还剩下"+pool.size()+"个连接");
        return proxy;
    }

    private synchronized void returnConnection(Connection connection){
        pool.add(connection);
        System.out.println("换回一个连接，还剩下"+pool.size()+"个连接");
    }



}
